package com.erji.common.utils;

import org.springframework.util.Base64Utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtils {
    public EncryptUtils() {
    }

    public static String encodeMD5String(String str) {
        return encode(str, "MD5");
    }

    public static String encodeSHAString(String str) {
        return encode(str, "SHA");
    }

    public static String encodeBase64String(String str) {
        return Base64Utils.encodeToString(str.getBytes());
    }

    public static String decodeBase64String(String str) {
        return new String(Base64Utils.decodeFromString(str));
    }

    private static String encode(String str, String method) {
        MessageDigest md = null;
        String dstr = null;

        try {
            md = MessageDigest.getInstance(method);
            byte[] e = md.digest(str.getBytes());
            dstr = toHexString(e);
            return dstr;
        } catch (NoSuchAlgorithmException var5) {
            var5.printStackTrace();
            return "";
        }
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder hs = new StringBuilder();
        String stmp = "";

        for(int n = 0; n < bytes.length; ++n) {
            stmp = Integer.toHexString(bytes[n] & 255);
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }

        return hs.toString();
    }
}
